import { FC } from "react"
import useGetQuestion from "../../hooks/useGetQuestion"
import { getComponentByType } from "../../questioncomponents"
import { QuestionInfoType, setSelectedId,moveComponent } from "../../store/ComponentReducer"
import style from './index.module.scss'
import classnames from 'classnames/bind'
import { useDispatch } from "react-redux"
import SortDndContext from "../../components/SortDndContext"
import SortableItem from "../../components/SortableItem"
const CBN = classnames.bind(style)


const MiddlePanel: FC = () => {
    const { componentList, selectedId } = useGetQuestion()
    const dispatch = useDispatch()
    const changeSelectId = (event:MouseEvent,fe_id:string)=>{
        event.stopPropagation()
        dispatch(setSelectedId(fe_id))
    }
    const componentListWidthId = componentList.map((item:QuestionInfoType)=>{
        return {
            id:item.fe_id,
            ...item
        }
    })
    const ondrag = (oldIndex:number,newIndex:number)=>{
        // console.log(oldIndex,newIndex)
        dispatch(moveComponent({oldIndex,newIndex}))
    }
    return <>
    <SortDndContext items={componentListWidthId} ondrag={ondrag}>
    {
        componentList.filter((c)=>{
            return !c.hide
        }).map((c) => {
            const { type, props, fe_id,lock } = c
            const Component = getComponentByType(type)
            const defaultClass = CBN({
                'selctedBox':true,
                'isselect':selectedId === fe_id,
                'islock':lock
            })
            return Component ? 
            <SortableItem id={fe_id} key={fe_id}>
                <div  className={defaultClass} onClick={(event:any)=>{changeSelectId(event,fe_id)}}>
                    <div  className={CBN('notouch')}>
                        <Component.Component {...props}></Component.Component>
                    </div>
                </div>
            </SortableItem>
                
            : <></>
        })
    }
    </SortDndContext>
        

    </>
}

export default MiddlePanel